import json

from django.db.models import Q
from apps.software.migrations.utils import genToken
from django.http import JsonResponse
from  django.http import HttpResponse
# Create your views here.
from apps.software.models import User, Rights, Projectec, Ecm,HeatDevice,HeatLoss
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def getUser(request):
    data=json.loads(request.body.decode('utf-8'))
    username = data['username']
    password = data['password']
    user_info=list(User.objects.all().values()) #将set集合转变为list集合
    for u in user_info:
        if u['username']==username and u['password']==password:
            print("登录成功!")
            token=genToken.generateToken()
            return JsonResponse({'status':200,'token':token})
        else:
            return JsonResponse({'status':201})
#呈现菜单栏
def getRights(request):
    rights_List = list(Rights.objects.filter(parent_id=0).values())
    for rights in rights_List:
        right_id=rights['id']
        # print(right_id)
        children_list=list(Rights.objects.filter(parent_id=right_id).values())
        rights_List[right_id-1]['children']=children_list #向字典中添加children对象
    return JsonResponse({'status':200,'data':rights_List})

def hello(request):
    mod=User.objects
    userList=mod.filter(username='admin')
    for u in userList:
        print(u.id,u.username,u.password)
    return HttpResponse("hello world")
#呈现配电柜型号选择菜单栏
@csrf_exempt
def getEcm(request):
    dic1 = {}
    try:
        # 使用ORM获取所有配电柜信息
        list1 = Ecm.objects.values('name')
        print("list1=",list1)
        j = []
        for i in list(list1):
            j.append(i['name'])
        q = list(set(j))#配电柜型号列表
        #创建一个存放配电柜型号的空字典sendDeviceData
        for aa in q:
            dic1[aa] = []
            # for bb in aa:
            #     dic1[aa][0] = {}
        # 将配电柜型号对应的尺寸加入到字典中
        for team in q:
            obj_errors = Ecm.objects.using('default').filter(name=team).values()
            for i in obj_errors:
                dic1[team].append(i['size'])
        # 返回
        print(dic1)
        print(q)
        return JsonResponse({'code':1, 'dict1':dic1, 'data2':q})
    except Exception as e:
        # 如果出现异常，返回
        return JsonResponse({'code': 0, 'msg': "获取配电柜型号信息出现异常，具体错误：" + str(e)})

#获取配电柜尺寸的详细信息
def getEcz(request):
    # 接收传递过来的配电柜尺寸--- axios默认是json --- 字典类型（'inputstr'）-- data['inputstr']
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 使用ORM获取满足条件的配电柜信息 并把对象转为字典格式
        obj_ecz = Ecm.objects.filter(Q(size=data['eczdata'])& Q(name=data['ecmdata'])).values()
        # 把外层的容器转为List
        ecz = list(obj_ecz)
        ecz_info=ecz[0]
        ecz_width=ecz_info['width']
        ecz_height=ecz_info['height']
        ecz_depth=ecz_info['depth']
        ecz_k=ecz_info['k']
        # 返回
        return JsonResponse({'code': 1, 'ecw': ecz_width, 'ech':ecz_height, 'ecd':ecz_depth, 'eck':ecz_k})
    except Exception as e:
        # 如果出现异常，返回
        return JsonResponse({'code': 0, 'msg': "查询学生信息出现异常，具体错误：" + str(e)})

#获得当前项目选择的配电柜信息
def getEc(request):
    try:
        # 使用ORM获取所有配电柜信息 并把对象转为字典格式
        obj_ecs = Projectec.objects.all().values()
        # 把外层的容器转为List
        ecs = list(obj_ecs)
        # 返回
        return JsonResponse({'code':1, 'data':ecs})
    except Exception as e:
        # 如果出现异常，返回
        return JsonResponse({'code': 0, 'msg': "获取信息出现异常，具体错误：" + str(e)})

#添加选择的配电柜书籍到数据库
def add_Ec(request):
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 添加到数据库
        obj_ec = Projectec(ecm=data['ecm'],ecz=data['ecz'],ecp=data['ecp'],heatloss=data['heatloss'],
                              ecw=data['ecw'],ech=data['ech'],ecd=data['ecd'],eck=data['eck'],)
        # 执行添加
        obj_ec.save()
        # 使用ORM获取所有选择的配电柜的信息 并把对象转为字典格式
        obj_ecs = Projectec.objects.all().values()
        # 把外层的容器转为List
        ecs = list(obj_ecs)
        # 返回
        return JsonResponse({'code': 1, 'data': ecs})
    except Exception as e:
        return JsonResponse({'code':0 , 'msg': "添加到数据库出现异常，具体原因：" + str(e)})

#修改选择的配电柜数据到数据库
def update_Ec(request):
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 查找到要修改的配电柜信息
        obj_ec = Projectec.objects.get(id=data['id'])
        # 依次修改
        obj_ec.ecm = data['ecm']
        obj_ec.ecz = data['ecz']
        obj_ec.ecp = data['ecp']
        obj_ec.ecw = data['ecw']
        obj_ec.ech = data['ech']
        obj_ec.ecd = data['ecd']
        obj_ec.eck = data['eck']
        # 保存
        obj_ec.save()
        # 使用ORM获取所有配电柜信息 并把对象转为字典格式
        obj_ecs = Projectec.objects.all().values()
        # 把外层的容器转为List
        ecs = list(obj_ecs)
        # 返回
        return JsonResponse({'code': 1, 'data': ecs})
    except Exception as e:
        return JsonResponse({'code':0 , 'msg': "修改保存到数据库出现异常，具体原因：" + str(e)})

#删除项目所选择的的配电柜信息
def delete_Ec(request):
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 查找到要删除的配电柜信息
        obj_ec = Projectec.objects.get(id=data['id'])
        # 删除
        obj_ec.delete()
        # 使用ORM获取项目选择的所有配电柜信息 并把对象转为字典格式
        obj_ecs = Projectec.objects.all().values()
        # 把外层的容器转为List
        ecs = list(obj_ecs)
        # 返回
        return JsonResponse({'code': 1, 'data': ecs})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "删除配电柜信息写入数据库出现异常，具体原因：" + str(e)})
def getHeatDevice(request): #添加元器件后 获取展示内容
    try:
        obj_heat=list(HeatDevice.objects.all().values())
        # print(obj_heat)
        return JsonResponse({'code':1,'data':obj_heat})
    except Exception as e:
        return JsonResponse({'code':0,'msg': "获取信息出现异常，具体原因：" + str(e)})
def getComponentGroup(request):
    dic1 = {}
    try:
        obj_device = list(HeatLoss.objects.values("group"))
        j = []
        for i in obj_device:
            j.append(i['group'])
        q = list(set(j))  # 配电柜型号列表
        for aa in q:
            dic1[aa] = []
            # for bb in aa:
            #     dic1[aa][0] = {}
        # 将配电柜型号对应的尺寸加入到字典中
        for team in q:
            obj_errors = list(HeatLoss.objects.filter(group=team).values())
            # print("obj_errors=", obj_errors)
            for i in obj_errors:
                dic1[team].append(i['dloss'])
        # 返回
        # print(dic1)
        # print(q)
        return JsonResponse({'code': 1, 'data1': dic1, 'data2': q})
    except Exception as e:
        # 如果出现异常，返回
        return JsonResponse({'code': 0, 'msg': "获取配电柜型号信息出现异常，具体错误：" + str(e)})
def sendDeviceData(request):
    try:
        data=json.loads(request.body.decode('utf-8'))
        print("data=",data)#dloss=data["deviceName"]
        obj_list=list(HeatLoss.objects.filter(dloss=data["deviceName"]).values())
        print(obj_list)
        return JsonResponse({'code':1,'data':obj_list})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "获取热损耗数据信息出现异常，具体错误：" + str(e)})

def submitDevice(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 添加到数据库
        obj_device = HeatDevice(device=data['deviceName'], num=data['num'], heat_before=data['beforeHeatLoss'],
                           factor=data['factor'], heat_after=data['initHeatLoss'],group=data['componentGroup'])
        # 执行添加
        obj_device.save()
        # 使用ORM获取所有选择的装置的信息 并把对象转为字典格式
        obj_ecs = HeatDevice.objects.all().values()
        # 把外层的容器转为List
        ecs = list(obj_ecs)
        # 返回
        return JsonResponse({'code': 1, 'data': ecs})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "获取设备数据信息出现异常，具体错误：" + str(e)})
def deleteDevice(request):
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 查找到要删除的配电柜信息
        obj_device = HeatDevice.objects.get(id=data['id'])
        # 删除
        obj_device.delete()
        # 使用ORM获取项目选择的所有配电柜信息 并把对象转为字典格式
        objAllInfo = Projectec.objects.all().values()
        # 把外层的容器转为List
        info = list(objAllInfo)
        # 返回
        return JsonResponse({'code': 1, 'data': info})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "删除配电柜信息写入数据库出现异常，具体原因：" + str(e)})
def submitDeviceData(request):
    data = json.loads(request.body.decode("utf-8"))
    try:
        if(data['heatloss']==0 or data['heatloss']==''):
            dataTotal=0
            list1 = list(HeatDevice.objects.values('heat_after'))
            print("list1=", list1)
            list_val = []
            for i in list1:
                list_val.append(i['heat_after'])
            print(list_val)
            for j in list_val:
                dataTotal+=float(j)
            print(dataTotal)
            Projectec_data=Projectec(heatloss=dataTotal)
            Projectec_data.save()
        else:
            Projectec_data=Projectec(heatloss=data['heatloss'])
            Projectec_data.save()
        #添加完成后进行删库操作
        obj_heat = list(HeatDevice.objects.all().values())
        # print(obj_heat)
        deleteAllData()
        return JsonResponse({'code': 1, 'data': obj_heat})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "删除配电柜信息写入数据库出现异常，具体原因：" + str(e)})
def deleteAllData():
    data=HeatDevice.objects.all().delete()
    print("删除成功")